package com.xinhua.web.servlet;

import com.xinhua.domain.Login;
import com.xinhua.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import sun.rmi.runtime.Log;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

//登录
@WebServlet("/LoginServlet")
public class LoginSevrlrt extends HttpServlet {
    private QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username + "" + password);
        List<Login> query = null;
        try {
            query = queryRunner.query("select * from day23.login where username=? and password=?", new BeanListHandler<Login>(Login.class), username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        for (Login l : query) {
            int id = l.getId();
            req.getSession().setAttribute("uuid", id);
            String username1 = l.getUsername();
            String password1 = l.getPassword();
            if (username.equals(username1) && password.equals(password1)) {
                req.getRequestDispatcher("/findServlet").forward(req, resp);
            }
        }
        req.setAttribute("msg", "账号或密码错误");
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
    }
}
